<template>
  <div class="page-padding-bg" style="position: relative;width: 100%;">

    <div class="user">
      <div class="user_title">
        <div> <span style="    white-space: nowrap;">用户名：</span><lay-input size="sm" placeholder="请输入" v-model="s_name" @keydown.enter="search_table"></lay-input></div>
        <div> <span>姓名：</span><lay-input size="sm" placeholder="请输入" v-model="s_description" @keydown.enter="search_table"></lay-input></div>
        <div>
          <lay-button class="btn-search" size="sm" type="normal" @click="search_table"> 查询</lay-button>
          <lay-button class="btn-resert" size="sm" @click="resert">重置</lay-button>
        </div>
      </div>
      <div class="user_btn">
        <lay-button class="btn-add" size="sm" type="primary" @click="add" v-permissions="'user_add'"> 新增</lay-button>

      </div>
      <div class="user_table">
        <lay-table :resize="true" :height="'100%'" :columns="columns" :data-source="dataSource">
          <template v-slot:operator="{ row }">
            <!-- {{ nowMenuBtnArr.includes('删除') }} -->

            <lay-button class="btn-edit" size="xs" type="primary" v-permissions="'user_edit'" @click="edit_table(row)"> 修改</lay-button>
            <lay-button class="btn-delete" size="xs" type="danger" v-permissions="'user_delete'" @click="del_table(row)"> 删除</lay-button>

            <lay-button class="btn-edit-pwd" size="xs" type="" v-permissions="'edit_pwd'" @click="edit_pwd(row)"> 修改密码</lay-button>
            <lay-button class="btn-view" size="xs" @click="view_form(row)" v-permissions="'user_view'">查看</lay-button>
          </template>

          <template v-slot:signBase="{ row }">
            <!-- <img :src="row.signBase" alt="" style="height: 40px;"> -->
            <el-image v-if="row.signBase" style=" height: 40px" :src="row.signBase" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[row.signBase]" fit="cover" />
          </template>

          <template v-slot:userstatus="{ row }">
            <lay-switch v-model="row.userstatus" onswitch-text="开启" onswitch-value="0" unswitch-value="1" unswitch-text="关闭" @change="switch_change(row,$event)"></lay-switch>
          </template>

        </lay-table>

        <Pagination :currentPage="currentPage" :limit="limit" :total="total" @page_change="page_change"></Pagination>

      </div>

    </div>

    <!-- 修改密码 -->
    <lay-layer v-model="editPassVisible" :area="['500px', '400px']" :title="'修改密码'" :btn="edit_pwd_visible_opteron" :shadeClose="false">
      <div style="padding:  40px;">
        <lay-form :model="editFrom" required label-position="top" :rules="editPwdRule" ref="layFormRefEdit">

          <lay-form-item label="请输入新密码" prop="pass">
            <lay-input v-model="editFrom.pass" size="sm" placeholder="请输入新密码" type="password" password></lay-input>
          </lay-form-item>
          <lay-form-item label="请再次输入新密码" prop="againPass" :label-width="200">
            <lay-input v-model="editFrom.againPass" size="sm" placeholder="请再次输入新密码" type="password" password></lay-input>
          </lay-form-item>

        </lay-form>
      </div>
    </lay-layer>

    <!-- 弹层 -->
    <lay-layer :teleportDisabled="true" class="down_layer" v-model="is_visible" :area="['800px', '730px']" :title="visibleTitle" :btn="isAddEdit=='view'?'':visible_opteron" :shadeClose="false">
      <div style="padding: 20px 40px 20px 20px;">
        <lay-form :model="form" ref="layFormRef11" :rules="rules5">
          <lay-form-item label="姓名" prop="description" required>
            <lay-input v-model="form.description" size="sm" placeholder="请输入" :disabled="isAddEdit=='view'"></lay-input>
          </lay-form-item>

          <lay-form-item label="性别" prop="gender" required>
            <lay-select v-model="form.gender" placeholder="请选择" style="width: 100%;" size="sm" :disabled="isAddEdit=='view'">
              <lay-select-option value="男" label="男"></lay-select-option>
              <lay-select-option value="女" label="女"></lay-select-option>
            </lay-select>
          </lay-form-item>
          <lay-form-item label="用户名" prop="name" required>
            <lay-input v-model="form.name" size="sm" placeholder="请输入" :disabled="isAddEdit!='add'"></lay-input>
          </lay-form-item>
          <lay-form-item label="密码" prop="upasswd" v-if="isAddEdit=='add'" required>
            <lay-input v-model="form.upasswd" size="sm" placeholder="请输入" type="password" password :disabled="isAddEdit=='view'"></lay-input>
          </lay-form-item>

          <lay-form-item label="手机号" prop="phonenum" required>
            <lay-input v-model="form.phonenum" size="sm" placeholder="请输入" :disabled="isAddEdit=='view'"></lay-input>
          </lay-form-item>

          <lay-form-item label="评委类型" prop="judgeType" required>
            <lay-select v-model="form.judgeType" allow-clear multiple placeholder="请选择" style="width: 100%;" size="sm" :disabled="isAddEdit=='view'">
              <lay-select-option value="0" label="日"></lay-select-option>
              <lay-select-option value="1" label="周"></lay-select-option>
              <lay-select-option value="2" label="月"></lay-select-option>
            </lay-select>
          </lay-form-item>

          <lay-form-item label="部门" prop="orgId" required>

            <lay-tree-select v-model="form.orgId" :data="orgList" :replaceFields="{id:'orgId',title:'orgName',children:'children'}" placeholder="请选择" style="width: 100%;" :disabled="isAddEdit=='view'"></lay-tree-select>
            <!-- <lay-select v-model="form.orgId" placeholder="请选择" style="width: 100%;" size="sm" :disabled="isAddEdit=='view'">
  <lay-select-option :value="item.orgId" :label="item.orgName" v-for="item in orgList" :key="item.orgId"></lay-select-option>
</lay-select> -->
          </lay-form-item>

          <lay-form-item label="岗位证书" prop="certificate" required>
            <lay-radio-group name="action" v-model="form.certificate" :disabled="isAddEdit=='view'">
              <lay-radio value="1">有</lay-radio>
              <lay-radio value="0">无</lay-radio>

            </lay-radio-group>
          </lay-form-item>

          <lay-form-item label="角色" prop="name" required>
            <lay-select v-model="form.rolecodeList" multiple allow-clear placeholder="请选择" style="width: 100%;" size="sm" :disabled="isAddEdit=='view'">
              <lay-select-option :value="item.rolecode" :label="item.rolename" v-for="item in roleList" :key="item.rolecode"></lay-select-option>
            </lay-select>
          </lay-form-item>

          <lay-form-item label="状态" prop="userstatus" required>
            <lay-switch v-model="form.userstatus" onswitch-text="开启" unswitch-text="关闭" :disabled="isAddEdit=='view'"></lay-switch>
          </lay-form-item>
          <lay-form-item label="头像" prop="avatar">
            <!-- :url="uploadUrl"  :headers="{'saToken':system.token}" -->
            <lay-upload @done="getUploadFile2" :url="uploadUrl" :headers="{'saToken':system.token}" :disabled="isAddEdit=='view'" :beforeUpload="beforeUpload">
              <template #preview>
                <div class="easy-wrap" v-if="form.avatar">
                  <!-- <img :src="form.avatar" style="width:62.9px;height:63.2px" /> -->
                  <el-image v-if="form.avatar" style=" height: 40px;width: 50px; " :src="form.avatar" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[form.avatar]" fit="cover" />
                  <!-- <img :src="form.signBase" style="width:62.9px;height:63.2px" /> -->
                </div>
              </template>
            </lay-upload>
          </lay-form-item>
          <!-- <lay-form-item label="电子签章" prop="signBase">
            <lay-avatar></lay-avatar>
          </lay-form-item> -->
          <lay-form-item label="描述" prop="remark">
            <lay-textarea placeholder="请输入描述" v-model="form.remark" rows="3" show-count :disabled="isAddEdit=='view'">
            </lay-textarea>
          </lay-form-item>

        </lay-form>
      </div>
    </lay-layer>

  </div>
</template> 

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import http from "@/http";
import { layer } from "@layui/layui-vue";
import { time_YY_DD_MM_HH_MI_SS } from "@/tools/time";
import Pagination from "@/components/pagination.vue";
import { useCounterStore } from "@/current";
import { storeToRefs } from "pinia";
import { uploadBaseURL } from "@/http";
const store = useCounterStore();
const { nowMenuBtnArr, system } = storeToRefs(store); //  数据

interface formType {
  name: string;
  description: string;
  gender: string;
  structure: string;
  rolecodeList: [];
  remark: string;
  phonenum: string | number;
  userstatus: boolean;
  orgId: string | number;
  upasswd: string | number;
  signUrl: string;
  signBase: string;
  avatar: string;
  avatarBase: string;
  judgeType: string[];
  certificate: string | number;
}
// 控制弹层
const is_visible = ref<boolean>(false);
// 弹层标题
const visibleTitle = ref<string>("");
// 表格数据
const dataSource = ref([]);
//当前页码数
const pageNo = ref<number | string>(1);
// 每页的条数
const pageSize = ref<number | string>(10);
// 分页
const limit = ref(10);
const total = ref(0);
const currentPage = ref(1);
const isAddEdit = ref("");
const layFormRef11 = ref();

// 用户名
const s_name = ref(undefined);
// 姓名
const s_description = ref(undefined);

// 表单数据
const form = reactive<formType>({
  name: "",
  description: "",
  gender: "",
  structure: "",
  rolecodeList: [],
  remark: "",
  phonenum: "",
  userstatus: true,
  orgId: "",
  upasswd: "",
  signUrl: "",
  signBase: "",
  avatar: "",
  avatarBase: "",
  judgeType: [], //评委类型
  certificate: "", //评委证书
});

const rules5 = ref({
  upasswd: {
    validator(rule, value, callback, source, options) {
      console.log(rule, value, value.length);

      let reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]/;
      if (value.length < 8 || value.length > 18 || !reg.test(value)) {
        callback(new Error(`密码长度为8~18位 并且必须包含大小写和数字`));
      } else {
        return true;
      }
    },
  },
  phonenum: {
    validator(rule, value, callback, source, options) {
      console.log(rule, value.length);

      if (Number.isNaN(value * 1)) {
        callback(new Error(`${rule.field}格式不正确`));
      } else if (value.length !== 11) {
        callback(new Error(`${rule.field}长度不正确`));
      } else {
        return true;
      }
    },
  },
});

// 表格
const columns = ref([
  { title: "用户名", key: "name" },
  { title: "姓名", key: "description" },
  { title: "创建人", key: "creator" },
  { title: "创建时间", key: "createday", width: "180px" },
  { title: "状态", key: "userstatus", customSlot: "userstatus" },
  { title: "电子签章", key: "signBase", customSlot: "signBase" },
  { title: "操作", customSlot: "operator", key: "operator", width: "240px" },
]);

const uploadUrl = ref(
  import.meta.env.DEV ? `/api/pc/minio/uploadSingleFileByFileOrBucketName?bucketName=${"smokeface"}` : uploadBaseURL + `/pc/minio/uploadSingleFileByFileOrBucketName?bucketName=${"smokeface"}`
);
// 文件上传
const getUploadFile2 = async (filelist) => {
  console.log(filelist);
  const data = filelist.data ? JSON.parse(filelist.data) : [];
  form.avatar = data.data;

  // const res = await http.corsApi(uploadUrl,'post',{file:filelist.data[0]})
  // console.log(res);
};

const beforeUpload = async (file) => {
  console.log(file);
  // let base64Image: any = "";
  // if (file) {
  //   try {
  //     // 使用FileReader进行转换
  //     const reader = new FileReader();
  //     reader.readAsDataURL(file);

  //     // 当读取完成时，将Base64数据赋值给组件状态
  //     await new Promise((resolve, reject) => {
  //       reader.onload = () => resolve(reader.result);
  //       reader.onerror = (error) => reject(error);
  //     });

  //     base64Image = reader.result;

  //     // 2
  //     // 假设您有一个Base64编码的图片字符串
  //     const base64ImageString = base64Image; // 实际的Base64字符串会更长

  //     // 提取Base64数据部分（去掉前面的"data:image/jpeg;base64,"）
  //     const imageData = base64ImageString.split(",")[1];

  //     // 创建一个Image对象
  //     const img = new Image();

  //     // 设置Image对象的源为Base64数据
  //     img.src = `data:image/jpeg;base64,${imageData}`;
  //     // 创建一个Canvas元素
  //     const canvas = document.createElement("canvas");

  //     // 获取Canvas的2D绘图上下文
  //     const ctx = canvas.getContext("2d");
  //     // 假设您希望压缩后的图片最大宽度为maxWidth，最大高度为maxHeight
  //     const maxWidth = 800;
  //     const maxHeight = 600;

  //     // 等待图片加载完成后再获取实际宽高
  //     img.onload = () => {
  //       // 计算压缩后的尺寸，保持宽高比
  //       const width = Math.min(img.naturalWidth, maxWidth);
  //       const height = Math.min(img.naturalHeight, maxHeight);

  //       // 设置Canvas尺寸
  //       canvas.width = width;
  //       canvas.height = height;

  //       // 绘制并压缩图片
  //       // 清空Canvas
  //       ctx.clearRect(0, 0, canvas.width, canvas.height);

  //       // 将图片绘制到Canvas上，按Canvas尺寸缩放
  //       ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

  //       // 使用toDataURL方法生成压缩后的Base64编码，指定压缩质量（0-1之间）
  //       const compressedBase64 = canvas.toDataURL("image/jpeg", 0.5); // desiredQuality 是您希望的压缩质量，比如0.8
  //       console.log(compressedBase64);
  //     };

  //     console.log(base64Image);
  //   } catch (error) {
  //     console.error("Error converting file to Base64:", error);
  //   }
  // }
  console.log(file.size);
  var isOver = true;
  if (file.size > 200000) {
    isOver = false;
    layer.msg(`文件大小不得超过200K`, { icon: 2 });
  }
  return new Promise((resolver) => resolver(isOver));
};

const get_list = async (page, size) => {
  const res = await http.corsApi("/secUser/page", "get", {
    pageNo: page,
    pageSize: size,
    name: s_name.value,
    description: s_description.value,
  });
  console.log(res);
  dataSource.value = res.data.list;
  total.value = res.data.totalCount;
};

// 新增
const add = async () => {
  isAddEdit.value = "add";
  visibleTitle.value = "新增";
  is_visible.value = true;
  get_role_list();
  get_org_list_tree();
  form.name = "";
  form.description = "";
  form.gender = "";
  form.structure = "";
  form.rolecodeList = [];
  form.remark = "";
  form.phonenum = "";
  form.userstatus = true;
  form.orgId = "";
  form.upasswd = "";
  form.signUrl = "";
  form.signBase = "";
  form.avatar = "";
  form.avatarBase = "";
  form.judgeType = [];
  form.certificate = "";
};
// 修改
const edit_table = (row) => {
  console.log(row);
  isAddEdit.value = "edit";
  visibleTitle.value = "修改";
  is_visible.value = true;
  get_role_list();
  get_user_detail(row.name);
  get_org_list_tree();
  form.name = row.name;
  form.description = row.description;
  form.gender = row.gender;
  form.structure = row.structure;
  // form.rolecodeList = row.rolecodeList;
  form.remark = row.remark;
  form.phonenum = row.phonenum;
  form.userstatus = row.userstatus == 0 ? true : false;
  form.orgId = row.orgId;
  form.upasswd = row.upasswd;
  form.signUrl = row.signUrl;
  form.signBase = row.signBase;
  form.avatar = row.avatar;
  form.avatarBase = row.avatarBase;
  form.certificate = row.certificate;
};
// 删除
const del_table = (row) => {
  layer.confirm("确认要删除吗？", {
    btn: [
      {
        text: "确认",
        callback: async (id) => {
          const res = await http.corsApi("/secUser/batch", "delete", [row.name]);
          console.log(res);
          if (res.data) {
            await get_list(pageNo.value, pageSize.value);

            await layer.confirm("删除成功", { icon: 1 });
          }
          layer.close(id);
        },
      },
      {
        text: "取消",
        callback: (id) => {
          layer.close(id);
        },
      },
    ],
  });
};

// 修改密码
const editFrom = ref({
  pass: "",
  againPass: "",
});
const editPassVisible = ref(false);
const layFormRefEdit = ref();
const edit_pwd_visible_opteron = ref([
  {
    text: "确认",
    callback: async () => {
      layFormRefEdit.value.validate(async (isValidate, model, errors) => {
        console.log(isValidate);
        if (isValidate) {
 
          const res = await http.corsApi("/secUser/updatePassword", "put", { id: nowId.value, upasswd: editFrom.value.againPass });
          console.log(res);
          if (res.data) {
            layer.confirm("密码修改成功", { icon: 1 });
            await get_list(pageNo.value, pageSize.value);
            editPassVisible.value = false;
          }
        }
      });
    },
  },
  {
    text: "取消",
    callback: () => {
      editPassVisible.value = false;
      //   layer.confirm("取消操作", { shade: false,icon:2 });
    },
  },
]);
const nowId = ref("");
const edit_pwd = (row) => {
  console.log(row);
  editPassVisible.value = true;
  editFrom.value.pass = "";
  editFrom.value.againPass = "";
  nowId.value = row.name;
};
// 修改密码校验
const editPwdRule = ref({
  pass: {
    // min: 8,
    // max: 18,

    validator(rule, value, callback, source, options) {
      let reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]/;
      if (value.length < 8 || value.length > 18 || !reg.test(value)) {
        callback(new Error(`密码长度为8~18位 并且必须包含大小写和数字`));
      } else if (editFrom.value.pass != value) {
        callback("两次密码输入不一致");
      } else {
        return true;
      }
    },
  },
  againPass: {
    validator(rule, value, callback, source, options) {
      // console.log(value);
      // console.log(editFrom.value.pass);
      // console.log(editFrom.value.pass != value);

      if (editFrom.value.pass != value) {
        callback("两次密码输入不一致");
      } else {
        return true;
      }
      // if (value < 18) {
      //   callback(new Error(`${rule.field}太过于年轻`));
      // } else {
      //   return true;
      // }
    },
  },
});

// 修改状态
const switch_change = async (row, e) => {
  console.log(row, e);
  const res = await http.corsApi(`/secUser/${row.name}/updateUserstatus/${e}`, "put", {});
  console.log(res);

  if (res.data) {
    layer.msg("状态修改成功", { time: 1500, icon: 1 });

    await get_list(pageNo.value, pageSize.value);
  }
};

// 查询
const search_table = async () => {
  console.log(s_description.value);
  console.log(s_name.value);

  await get_list(pageNo.value, pageSize.value);
};

// 重置
const resert = async () => {
  s_name.value = undefined;
  s_description.value = undefined;
  await get_list(pageNo.value, pageSize.value);
};

// 查看
const view_form = async (row) => {
  console.log(row);

  await get_role_list();
  isAddEdit.value = "view";
  visibleTitle.value = "查看";
  is_visible.value = true;
  await get_user_detail(row.name);
  await get_org_list_tree();
  form.name = row.name;
  form.description = row.description;
  form.gender = row.gender;
  form.structure = row.structure;
  form.remark = row.remark;
  form.phonenum = row.phonenum;
  form.userstatus = row.userstatus == 0 ? true : false;
  form.orgId = row.orgId;
  form.signUrl = row.signUrl;
  form.signBase = row.signBase;
  form.avatar = row.avatar;
  form.avatarBase = row.avatarBase;
};
// 弹层操作
const visible_opteron = ref([
  {
    text: "确认",
    callback: async () => {
      //   layer.confirm("确认操作", { shade: false,icon:1 });
      // console.log(form);

      // return false

      console.log(form);

      if (isAddEdit.value == "view") {
        is_visible.value = false;
        return false;
      }

      console.log(form.judgeType.join(","));

      layFormRef11.value.validate(async (isValidate, model, errors) => {
        if (isValidate) {
          let method = "";
          if (isAddEdit.value == "add") {
            method = "post";
          } else if (isAddEdit.value == "edit") {
            method = "put";
          }

         

  

          const res = await http.corsApi("/secUser", method, {
            // createday: time_YY_DD_MM_HH_MI_SS(new Date().getTime()), //创建时间
            // creator: system.value.description,
            description: form.description,
            gender: form.gender, 
            identityCard: new Date().getTime(),
            name: form.name,
            orgId: form.orgId,
            phonenum: form.phonenum,
            remark: form.remark,
            rolecodeList: form.rolecodeList,
            upasswd: isAddEdit.value == "add" ? form.upasswd : undefined,
            userstatus: form.userstatus ? "0" : "1",
            signUrl: form.signUrl,
            signBase: form.signBase,
            avatar: form.avatar,
            avatarBase: isAddEdit.value == "add" ? form.avatarBase : "",

            judgeType: form.judgeType.join(","),
            certificate:form.certificate
          });
          console.log(res);
          if (res.data) {
            layer.confirm(method == "post" ? "添加成功" : "修改成功", { icon: 1 });
            await get_list(pageNo.value, pageSize.value);
            is_visible.value = false;
          }
        }
      });
    },
  },
  {
    text: "取消",
    callback: () => {
      is_visible.value = false;
      //   layer.confirm("取消操作", { shade: false,icon:2 });
    },
  },
]);

// 分页事件
const page_change = async (page, limt) => {
  console.log(page, limt);
  console.log(pageNo.value, pageSize.value);
  currentPage.value = page;
  pageNo.value = currentPage.value;
  await get_list(page, limt);
};

const roleList = ref([]);
const get_role_list = async () => {
  const res = await http.corsApi("/secRole", "get", {});
  console.log(res);
  roleList.value = res.data;
};

// 获取用户的详细信息
const get_user_detail = async (id) => {
  const res = await http.corsApi(`/secUser/${id}`, "get", {}, { is_msg: false });
  console.log(res);
  if (res.data) {
    form.rolecodeList = res.data.rolecodeList;
    form.judgeType = res.data.judgeType?.split(",");
    form.certificate = res.data.certificate
  } else {
    form.rolecodeList = [];
    form.judgeType = [];
    form.certificate = ''
  }
};

const orgList = ref([]);
// 获取部门列表
const get_org_list_tree = async () => {
  // const res = await http.corsApi("/secOrg/getOrgAllTreeData", "get", {});
  const res = await http.corsApi("/secOrg", "get", {});
  console.log(res);
  orgList.value = res.data;
};

// 页面初始化
onMounted(async () => {
  await get_list(pageNo.value, pageSize.value);

  console.log(dataSource.value);
});
</script>

<style scoped lang="scss">
.user {
  width: 100%;
  max-height: 100%;
  background-color: #fff;
  padding: 20px;

  box-sizing: border-box;
  &_title {
    display: flex;
    justify-content: space-between;
    > div {
      display: flex;
      align-items: center;
      margin-right: 35px;
      span {
        width: 60px;
        text-align: right;
      }
      .layui-input {
        width: 300px;
      }
    }
  }

  &_btn {
    // margin-right: 8px;
    margin-top: 20px;
  }
  &_table {
    margin-top: 20px;
  }
}

:deep(.layui-upload) {
  .layui-btn {
    height: 30px;
    line-height: 30px;
  }
}

:deep(.el-image-viewer__wrapper .el-image-viewer__canvas .el-image-viewer__img) {
  // transform: scale(0.6) rotate(0deg) ;
}
:deep(.el-image-viewer__canvas img) {
  background-color: #fff;
}

:deep(.layui-layer) {
  // top: 50% !important;
  // transform: translateY(-50%);
}
.down_layer {
  transform: translateY(-100px);
  background-color: #f00;
}

.page-padding-bg {
  min-height: calc(100vh - 120px);
}
</style>